<template>
  <el-dialog :visible.sync="value" :before-close="cancel" append-to-body width="60%">
    <div class="createPost-container" style="max-height:70vh; overflow: auto">
      <el-form
        class="form-container"
        :model="form"
        :rules="rules"
        ref="refForm"
        label-width="100px"
        :inline="true"
      >
        <el-form-item label="发送对象:" prop="sendObj">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-checkbox label="会员层级" name="isMemberLevelId" v-model="form.isMemberLevelId"></el-checkbox>
            </el-col>
            <el-col :span="16">
              <el-select
                :collapse-tags="true"
                v-model="form.memberLevelId"
                placeholder="请选择会员层级"
                :multiple="true"
              >
                <el-option
                  v-for="item in levelList"
                  :key="item.levelId"
                  :label="item.name"
                  :value="item.levelId"
                ></el-option>
              </el-select>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-checkbox label="会员帐号" name="isMemberAccount" v-model="form.isMemberAccount"></el-checkbox>
            </el-col>
            <el-col :span="16">
              <el-input
                type="textarea"
                class="article-textarea"
                autosize
                placeholder="请输入会员账户"
                v-model="form.memberAccount"
              ></el-input>
            </el-col>
          </el-row>
          <div class="tips">注:1.会员层级和会员账号至少要选择/填写一项</div>
          <div class="tips">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2.支持输入多个会员账号，以","号分隔</div>
        </el-form-item>
        <el-row :gutter="20">
          <el-form-item label="主题:" prop="title">
            <el-col :span="16">
              <el-input
                type="textarea"
                maxlength="45"
                class="article-textarea"
                autosize
                placeholder="请输入内容"
                v-model="form.title"
              ></el-input>
            </el-col>
            <el-col :span="8">
              <el-checkbox label="活动信件" name="letterType" v-model="form.letterType"></el-checkbox>
            </el-col>
          </el-form-item>
        </el-row>
        <el-form-item label="内容:" prop="content">
          <Tinymce :height="400" ref="editor" v-model="form.content"/>
          <div class="preview-box">
            <el-button @click="handlePcPreview">预览PC效果</el-button>
            <el-button @click="handleMobilePreview">预览APP效果</el-button>
            <el-row>
              <pc-preview
                v-show="preview.pc"
                :name="form.memberAccount"
                :content="form.content"
                :time="form.sendTime"
              />
              <mobile-preview
                v-show="preview.moblie"
                :name="form.memberAccount"
                :content="form.content"
                :time="form.sendTime"
              />
            </el-row>
          </div>
        </el-form-item>
        <el-row>
          <el-col>
            <el-button
              v-loading="loading"
              style="margin: 10px 0;float:right"
              :disabled="isDisabled"
              type="primary"
              @click="doSave({
                 action: 'immediately',
                 form: {
                 name: 'refForm',
                 scrollToError: true
                 }})"
            >立即发送</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="发送时间:" class="postInfo-container-item" prop="sendTime">
            <el-date-picker
              v-model="form.sendTime"
              class="filter-item"
              start-placeholder="开始日期"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              align="center"
            ></el-date-picker>
          </el-form-item>

          <el-button
            v-loading="loading"
            style="margin-left: 10px 0;float:right"
            :disabled="isDisabled"
            type="primary"
            @click="doSave({
                 action: 'delay',
                 form: {
                 name: 'refForm',
                 scrollToError: true
                 }})"
          >定时发送</el-button>
        </el-row>
      </el-form>
    </div>
  </el-dialog>
</template>

<script>
import { noticeLetterAddApi } from '@/services/api/notice';
import { getUserLevelList } from '@/services/api/userLevel';
import { form } from '@/build';
import pcPreview from '../preview/pcPreview';
import mobilePreview from '../preview/mobilePreview';
import Tinymce from '@/components/Tinymce';

export default {
  name: 'add-notice-letter',
  components: {
    Tinymce,
    pcPreview,
    mobilePreview,
  },

  mixins: [form],

  props: ['value', 'id', 'rowData'],

  data() {
    return {
      form: {
        id: String(this.id),
        isMemberLevelId: undefined,
        isMemberAccount: undefined,
        memberLevelId: [],
        memberLevelName: undefined,
        memberAccount: undefined,
        letterType: 0,
        content: undefined,
        title: undefined,
        sendTime: new Date(),
        sendObj: undefined,
      },
      isDisabled: false,
      levelList: [],
      rules: {
        sendObj: {
          required: true,
          message: '请选择或者输入需要发送对象',
        },
        title: { required: true, message: '标题必须填写' },
        content: { required: true, message: '内容必须填写' },
      },
      preview: {
        pc: false,
        moblie: false,
      },
    };
  },
  computed: {},
  watch: {
    form: {
      handler(newName, oldName) {
        if (newName.memberLevelId.length) {
          this.form.isMemberLevelId = true;
        }
        if (newName.memberAccount) {
          this.form.isMemberAccount = true;
        }
        if (newName.memberLevelId.length || newName.memberAccount) {
          this.form.sendObj = '验证通过';
        } else {
          this.form.sendObj = undefined;
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    if (!_.isUndefined(this.rowData.row) && this.rowData.row.id) {
      let {
        memberLevelId,
        sendTime,
        memberLevelName,
        memberAccount,
        letterType,
      } = this.rowData.row;
      const arr = memberLevelName.split(',');
      const obj = {};
      arr.map((item) => {
        this.rowData.levelList.map((_item) => {
          if (item === _item.name) {
            obj[item] = _item.levelId;
          }
          return obj;
        });
      });
      memberLevelId = Object.values(obj);
      this.form = {
        ...this.rowData.row,
        sendTime: new Date(sendTime),
        memberLevelId,
        isMemberLevelId: !!memberLevelName,
        isMemberAccount: !!memberAccount,
        letterType: !!letterType,
      };
    }
    this.bindSave(noticeLetterAddApi, 'immediately', 'form', {
      beforeSend: (data) => {
        this.handleDisable();
        let {
          memberLevelId,
          sendTime,
          letterType,
          memberLevelName,
          content,
        } = data;
        const obj = {};
        const reg = /img class="wscnph" src="api/g;
        const newContent = content.replace(reg, 'img class="wscnph" src="/api');
        if (memberLevelId.length) {
          memberLevelId.map((item) => {
            this.levelList.map((_item) => {
              if (item === _item.levelId) {
                obj[item] = _item.name;
              }
              return obj;
            });
          });
          memberLevelName = Object.values(obj).join(',');
        }
        return {
          ...data,
          memberLevelId: memberLevelId.length ? memberLevelId.join(',') : '',
          memberLevelName: memberLevelName || '',
          letterType: letterType ? 1 : 0,
          sendTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          content: newContent,
        };
      },
      callback: ([result, data]) => {
        if (result) {
          this.$notify({
            title: '保存成功',
            type: 'success',
            duration: 2000,
          });
          this.cancel();
          this.$parent.getAll();
        } else {
          this.$notify({
            title: `保存失败.${data && data.message}`,
            type: 'error',
            duration: 2000,
          });
          this.handleDisable();
        }
      },
    });
    this.bindSave(noticeLetterAddApi, 'delay', 'form', {
      beforeSend: (data) => {
        this.handleDisable();
        let {
          memberLevelId,
          sendTime,
          letterType,
          memberLevelName,
          content,
        } = data;
        const obj = {};
        const reg = /img class="wscnph" src="api/g;
        const newContent = content.replace(reg, 'img class="wscnph" src="/api');
        if (memberLevelId.length) {
          memberLevelId.map((item) => {
            this.levelList.map((_item) => {
              if (item === _item.levelId) {
                obj[item] = _item.name;
              }
              return obj;
            });
          });
          memberLevelName = Object.values(obj).join(',');
        }
        return {
          ...data,
          memberLevelId: memberLevelId.length ? memberLevelId.join(',') : '',
          memberLevelName: memberLevelName || '',
          letterType: letterType ? 1 : 0,
          sendTime: moment(sendTime).format('YYYY-MM-DD HH:mm:ss'),
          content: newContent,
        };
      },
      callback: ([result, data]) => {
        if (result) {
          this.$notify({
            title: '保存成功',
            type: 'success',
            duration: 2000,
          });
          this.cancel();
          this.$parent.getAll();
        } else {
          this.$notify({
            title: `保存失败.${data && data.message}`,
            type: 'error',
            duration: 2000,
          });
          this.handleDisable();
        }
      },
    });
    // 获取会员层级列表
    this.bindGet(getUserLevelList, 'levelList', {});
    this.getAll();
  },
  methods: {
    cancel() {
      this.$emit('input', false);
    },
    // 预览pc
    handlePcPreview() {
      this.preview.moblie = false;
      this.preview.pc = !this.preview.pc;
    },
    // 预览mobile
    handleMobilePreview() {
      this.preview.pc = false;
      this.preview.moblie = !this.preview.moblie;
    },
    // 是否开启和禁用发送
    handleDisable() {
      this.isDisabled = !this.isDisabled;
    },
  },
};
</script>

<style lang="scss" scoped>
.image {
  width: 100px;
  height: 100px;
}
.tips {
  color: rgb(177, 176, 176);
  font-size: 14px;
}
</style>
